<?php

namespace App\Admin\Forms\User;

use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class PhoneForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input): mixed
    {

        $user = User::query()->where('id', $this->payload['id'])->first();
        if (!preg_match('/^1[3456789]\d{9}$/', $input['phone'])) {
            return $this->response()->error('请填写正确的手机号码');
        }
        //唯一验证
        if (User::query()->where('phone', $input['phone'])->where('id', '!=', $this->payload['id'])->exists()) {
            return $this->response()->error('手机号码已存在');
        }
        $user->phone = $input['phone'];
        $user->save();
        return $this->response()->success('操作成功')->refresh();

    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('phone')->default($this->payload['phone'])->required();
    }


}
